package com.cyou.nad.tag.form;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import org.apache.commons.lang.StringUtils;

import com.cyou.fz173.util.JacksonUtil;
import com.cyou.nad.utils.ReflectionUtils;

/**
 * example :
 * 	<s:select name="payPlan"  id="payPlan" list="#{'全部':'全部','AnP':'AnP','COST':'COST','COST-S':'COST-S'}" ></s:select>
 * 	<s:select name="adminId"  list="adminList" listKey="id" listValue="userName" ></s:select>
 * 在第二种方式中，adminList，是为了获取一个object list的名称，listKey是获取的这个objlist中的obj的某个字段，listValue也是obj中的某个字段
 * 所以最终获取的是 一个name ，一些key和一些value
 * @author luzhaoman
 *
 */
public class OptionTag extends SimpleTagSupport {
	
	private String name;
	
	private String list;
	
	private String listKey;
	
	private String listValue;
	
	@Override
	public void doTag() throws JspException, IOException {
		if(StringUtils.isBlank(name)){
			throw new JspException("OptionTag  name is null");
		}
		if(StringUtils.isBlank(list)){
			throw new JspException("OptionTag  list is null");
		}
		String defaultValue=getStrFromContext(name);
		List<String> keyList =new ArrayList<String>();
		List<String> valueList =new ArrayList<String>();
		bulidList(keyList, valueList);
		String html="";
		html=buliderHtml(defaultValue,keyList,valueList);
		getJspContext().getOut().print(html);
	}

	private String buliderHtml(String defaultValue, List<String> keyList, List<String> valueList) {
		StringBuilder sb = new StringBuilder();
		if(!keyList.isEmpty()&&keyList.size()==valueList.size()){
			int i=0;
			for (String string : valueList) {
				if(defaultValue!=null&&defaultValue.equalsIgnoreCase(string)){
					sb.append("<option value='"+string+"' selected>").append(keyList.get(i)).append("</option>\n");
				}else{
					sb.append("<option value='"+string+"'>").append(keyList.get(i)).append("</option>\n");
				}
				i++;
			}
		}
		return sb.toString();
	}

	private void bulidList(List<String> keyList, List<String> valueList) throws JspException {
		//list的形式分为：以#{打头和不以#{打头，此时需要listKey和listValue
		if(list.startsWith("#{")){
			String tmp = list.substring(2,list.length()-1);
			String[] arr = tmp.split(",");
			int i=0;
			for (String string : arr) {
				String[] item = string.split(":");
				if(item.length!=2)
					continue;
				keyList.add(trimQuot(item[1]));
				valueList.add(trimQuot(item[0]));
				i++;
			}
		}else{
			if(StringUtils.isBlank(listKey)||StringUtils.isBlank(listValue)){
				throw new JspException("when list is array   listKey and listValue must not null");
			}
			Object tmp = getValueFromContext(list);
			if(tmp!=null&& tmp instanceof List){//测试它左边的对象是否是它右边的类的实例
				List tmpList =  (List) tmp;
				if(!tmpList.isEmpty()){
					for (Object obj : tmpList) {//强行读取对象属性值，无视private和protected
						Object key = ReflectionUtils.getFieldValue(obj, listKey);
						Object value = ReflectionUtils.getFieldValue(obj, listValue);
						keyList.add(key+"");
						valueList.add(value+"");
					}
				}
			}
		}
	}

	private String trimQuot(String str) {
		if(StringUtils.isBlank(str)){
			return "";
		}
		return str.replace("'","").replace("\"","");
	}
	private Object getValueFromContext(String name) {
		//不管怎么样从某个地方获取到定义的list名所对应的。
		 JspContext jspContext = getJspContext();   
		 ServletRequest req =  ((PageContext) jspContext).getRequest();
		 HttpSession session =   ((PageContext) jspContext).getSession();
		 ServletContext application  = ((PageContext) jspContext).getServletContext();
		 
		 if(getJspContext().getAttribute(name)!=null){
			 return getJspContext().getAttribute(name);
		 }
		 if(req.getAttribute(name)!=null){
			 return req.getAttribute(name);
		 }
		 if(session.getAttribute(name)!=null){
			 return session.getAttribute(name);
		 }
		 if(application.getAttribute(name)!=null){
			 return application.getAttribute(name);
		 }
		 return null;
	}
	
	private String getStrFromContext(String name) {
		Object obj = getValueFromContext(name);
		if(obj==null)
			return "";
		 return StringUtils.trimToEmpty(obj.toString());
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getList() {
		return list;
	}

	public void setList(String list) {
		this.list = list;
	}

	public String getListKey() {
		return listKey;
	}

	public void setListKey(String listKey) {
		this.listKey = listKey;
	}

	public String getListValue() {
		return listValue;
	}

	public void setListValue(String listValue) {
		this.listValue = listValue;
	}
	
	
	public static void main(String[] args) {
		String json="'全部':'全部','AnP':'AnP','COST':'COST','COST-S':'COST-S'";
		System.out.println(JacksonUtil.toArray(json, String.class));
	}
	
}
